package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.CommentRequest
import com.jiangnan.entity.CommentResponse
import com.jiangnan.repository.CommentRepository
import kotlinx.coroutines.launch

class CommentViewModel : ViewModel() {
  private val repo = CommentRepository()

  private val _comments = MutableLiveData<List<CommentResponse>>()
  val comments: LiveData<List<CommentResponse>> = _comments

  private val _error = MutableLiveData<String>()
  val error: LiveData<String> = _error

  // 当前回复目标
  var currentParentId: Long? = null
  var currentToUserId: Long? = null

  fun loadComments(page: Int = 0, size: Int = 20) {
    viewModelScope.launch {
      try {
        val res = repo.listComments(page, size)
        if (res.code == 1 && res.data != null) _comments.value = res.data!!
        else _error.value = res.msg
      } catch (e: Exception) {
        _error.value = e.message
      }
    }
  }

  fun postComment(userId: Long, content: String) {
    viewModelScope.launch {
      try {
        val req = CommentRequest(userId, currentParentId, currentToUserId, content)
        val res = repo.postComment(req)
        if (res.code == 1 && res.data != null) {
          // 更新本地列表
          val updated = _comments.value?.toMutableList() ?: mutableListOf()
          if (req.parentId == null) {
            updated.add(0, res.data)
          } else {
            updated.find { it.id == req.parentId }?.let { root ->
              val newReplies = root.replies.toMutableList().apply { add(0, res.data) }
              updated[updated.indexOf(root)] = root.copy(replies = newReplies)
            }
          }
          _comments.value = updated
          // 重置
          currentParentId = null
          currentToUserId = null
        } else _error.value = res.msg
      } catch (e: Exception) {
        _error.value = e.message
      }
    }
  }

  fun deleteComment(id: Long) {
    viewModelScope.launch {
      try {
        val res = repo.deleteComment(id)
        if (res.code == 1) loadComments()
        else _error.value = res.msg
      } catch (e: Exception) {
        _error.value = e.message
      }
    }
  }
}